package com.u.social.article.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.u.social.article.model.ArticleWithTopicDTO;
import com.u.social.article.service.IArticlesService;
import com.u.social.article.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: u-social
 * @description: 帖子消费类
 * @author: Alex Wu
 * @createDate: 2025-02-27 14:28
 **/
@Slf4j
@Service
@RocketMQMessageListener(topic = "article-topic", consumerGroup = "article-group",
        maxReconsumeTimes = 3)  // 配置死信队列最好配置最大消费次数，否则按照16次计算
public class ArticleConsumer  implements RocketMQListener<String> {

    @Autowired
    private IArticlesService articlesService;

    @Autowired
    private IRedisService redisService;
    @Override
    public void onMessage(String s) {
        log.info("receive article message: {}", s);
        // 存本地数据库与 Redis 缓存
        ArticleWithTopicDTO articleWithTopicDTO = JSON.parseObject(s, ArticleWithTopicDTO.class);
        try {
            articlesService.saveWithTopic(articleWithTopicDTO);
        }catch(Exception e) {
            log.error("article save db and cache error: {}", e.getMessage());
        }
    }
    // 暂时实现在本微服务上，后续会调用其他微服务
}
